<?php

namespace addons\rexam\controller;

use think\Exception;
use think\Session;

class Answer extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\rexam\Answer;
    }

    public function question(){
        if ($this->request->isAjax()) {
            $param = input();
            $where = array();

            $where['user_id'] = $this->auth->id;
            $where['rexam_id'] = $param['rid'];
            $answer_one = $this->model
                ->where($where)
                ->find();

            $question_list = explode(',', $answer_one['rexamquestion_ids']);
            $qid = $question_list[$param['qnum']-1];

            $rexam_mode = new \app\admin\model\rexam\Rexam;
            $rexam_one = $rexam_mode->get(['id'=> $param['rid']]);

            if(empty($param['ana'])){
                $random=$rexam_one['randomdata'];
            }else{
                $random=0;
            }

            $question_mode = new \app\admin\model\rexam\Question;
            $quesion_one = $question_mode->load($qid, $random);

            $limit=array();
            if($rexam_one['limitdata'] && empty($param['ana'])){
                $question_limit = Session::get('rexam_'.$param['rid']);
                if($rexam_one['limitall']){
                    if(empty($question_limit['limitall'])){
                        $question_limit['limitall']=time() + $rexam_one['limitall'];
                        $question_limit['allcount']=$rexam_one['limitall'];
                    }else{
                        $question_limit['allcount'] = $question_limit['limitall'] - time();
                        if($question_limit['allcount']<0){
                            $question_limit['allcount']=0;
                        }
                    }
                }

                if($rexam_one['limitone']){
                    if(empty($question_limit['limitone'.$qid])){
                        $question_limit['limitone'.$qid]=time() + $rexam_one['limitone'];
                        $question_limit['onecount'.$qid]=$rexam_one['limitone'];
                    }else{
                        $question_limit['onecount'.$qid] = $question_limit['limitone'.$qid] - time();
                        if($question_limit['onecount'.$qid]<0){
                            $question_limit['onecount'.$qid]=0;
                        }
                    }
                }
                Session::set('rexam_'.$param['rid'], $question_limit);
                $limit=['allcount'=>$question_limit['allcount'], 'onecount'=>$question_limit['onecount'.$qid], 'limitall'=>$rexam_one['limitall'], 'limitone'=>$rexam_one['limitone']];
            }

            return $this->ajax_success('OK',array(
                "question" =>$quesion_one,
                "limit"=>$limit
            ));
        }
    }

    public function answer(){
        if ($this->request->isAjax()) {
            $param = input();
            $where = array();
            $data = array();

            $question_mode = new \app\admin\model\rexam\Question;

            foreach ($param as $key => $vo){
                if(substr( $key,0,8) == 'question'){
                    $data[substr($key, 8)]=$vo;
                }
                if($key == 'aid'){
                    $where['id']=$vo;
                }
            }
            $answer_one = $this->model->get($where);
            $answerarr = array();
            $rightcount = 0;
            foreach ($data as $key => $vo){
                $right = $question_mode->check($key, $vo);
                if($right){
                    $rightcount++;
                }
                $questionone = [
                    'qid'=>$key,
                    'ans'=>$vo,
                    'res'=>$right
                ];
                $answerarr[]=$questionone;
            }
            $answerjson = json_encode($answerarr);

            if(empty($param['save'])){
                $rexam_mode = new \app\admin\model\rexam\Rexam;
                $rexam_one = $rexam_mode->get(['id'=>$answer_one['rexam_id']]);
                $points = 0;
                if($rexam_one['pointsdata']){
                    $points = $rexam_one['pointslimit'] * $rightcount / $answer_one['question_count'];
                }
                $this->model->allowField(true)->save(['answerjson'=>$answerjson, 'right_count'=>$rightcount, 'points'=>$points, 'overtime'=>time()], $where);
                if($points){
                    $user_mode = new \app\admin\model\rexam\User;
                    $user_mode->where(['user_id'=>$this->auth->id])->setInc('points', $points);
                }
            }else{
                $this->model->allowField(true)->save(['answerjson'=>$answerjson], $where);
            }

            return $this->ajax_success('OK');
        }
    }

    public function ranking(){
        if($this->request->isAjax()){
            $date_area = [];
            $time_area = [];
            $param = input();
            $where = array();
            switch ($param['type']){
                case 3:
                    $date_area[] = date('Y-m-d', strtotime('saturday - 6 day', time()));
                    $date_area[] = date('Y-m-d', strtotime('saturday', time()));
                    $time_area[] = strtotime(date('Y-m-d', strtotime('saturday - 6 day', time())).' 00:00:00');
                    $time_area[] = strtotime(date('Y-m-d', strtotime('saturday', time())).' 23:59:59');
                    $where['overtime'] = array('between', $time_area);
                    break;
                case 2:
                    $date_area[] = date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
                    $date_area[] = date('Y-m-d', strtotime('+1 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))-86400);
                    $time_area[] = strtotime(date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')).' 00:00:00');
                    $time_area[] = strtotime(date('Y-m-d', strtotime('+1 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))-86400).' 23:59:59');
                    $where['overtime'] = array('between', $time_area);
                    break;
                case 1:
//                    mktime ($hour = null, $minute = null, $second = null, $month = null, $day = null, $year = null, $is_dst = null)
                    $date_area[] = date('Y-m-d' ,mktime(0, 0, 0, 1,1, date("Y")));
                    $date_area[] = date('Y-m-d' ,mktime(0, 0, 0, 12,31, date("Y")));
                    $time_area[] = strtotime(date('Y-m-d' ,mktime(0, 0, 0, 1,1, date("Y"))).' 00:00:00');
                    $time_area[] = strtotime(date('Y-m-d' ,mktime(0, 0, 0, 12,31, date("Y"))).' 23:59:59');
                    $where['overtime'] = array('between', $time_area);
                    break;
                case 0:
                default:
                    $where['id'] = array('gt', 0);
                    break;
            }

            $list = $this->model
                ->where($where)
                ->field('user_id, count(*) as countanswer, sum(points) as sumpoints')
                ->group('user_id')
                ->order('sumpoints desc')
                ->page($param['page'], $this->config['perranking'])
                ->select();

//            $sql = $this->model->getLastSql();

            $res = array();
            $user_mode = new \app\admin\model\rexam\User;
            foreach ($list as $k => $v){
                $user_one = $user_mode
                    ->with(['sysuser', 'rexamgroup'])
                    ->where(['user_id'=>$v['user_id']])
                    ->find();

                $res[] = [
                    'rank'=>($param['page']-1)*$this->config['perranking']+$k+1,
                    'user_id'=>$v['user_id'],
                    'nickname'=>$user_one['sysuser']['nickname'],
                    'name'=>$user_one['name'],
                    'group_name'=>$user_one['rexamgroup']['name'],
                    'avatar'=>cdnurl($user_one['sysuser']['avatar']),
                    'countanswer'=>$v['countanswer'],
                    'sumpoints'=>$v['sumpoints']
                ];
            }
            
            return $this->ajax_success('OK', ['count'=>count($res), 'ranking'=>$res, 'date'=>$date_area]);
        }
    }
}